package fu.capstone.hanoicityguide.presentation.fragment.itinerary;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SearchView;
import fu.capstone.hanoicityguide.R;
import fu.capstone.hanoicityguide.business.bo.itinerary.ItineraryBO;
import fu.capstone.hanoicityguide.business.bo.itinerary.ItineraryBOImp;
import fu.capstone.hanoicityguide.business.model.Itinerary;
import fu.capstone.hanoicityguide.presentation.adapter.ListItineraryAdapter;

@SuppressLint("ValidFragment")
public class ListItineraryFragment extends Fragment implements
		SearchView.OnQueryTextListener, SearchView.OnCloseListener {

	private ItineraryBO itineraryBO;
	private ArrayList<Itinerary> arrItinerary;
	private String sorter;
	private ListItineraryAdapter itineraryAdapter = null;
	private ListView listItinerary = null;
	private SearchView searchView;
	private String keyword;
	private boolean[] itemChecked;
	private boolean[] oldChecked;
	private DrawerLayout drawer;

	public ListItineraryFragment(DrawerLayout drawer) {
		this.drawer = drawer;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// init
		View listItineraryFragment = inflater.inflate(
				R.layout.fragment_list_itinerary, container, false);
		try {
			setHasOptionsMenu(true);
			itineraryBO = new ItineraryBOImp(container.getContext());
			listItinerary = (ListView) listItineraryFragment
					.findViewById(R.id.listItinerary);

			// set keyword and sorter
			setKeyword("");
			// setFilter("All");
			setSorter(getResources().getStringArray(R.array.sorter_items)[0]);

			// get all list Itinerary
			arrItinerary = new ArrayList<Itinerary>();
			arrItinerary = itineraryBO.listItinerary(getKeyword(), getSorter());
			// Toast.makeText(getActivity(), "Iti lenght : " +
			// arrItinerary.size(),Toast.LENGTH_SHORT).show();
			itineraryAdapter = new ListItineraryAdapter(getActivity(),
					R.layout.adapter_list_itinerary, arrItinerary);

			// set listview adapter and create event for items click
			listItinerary.setAdapter(itineraryAdapter);

			listItinerary.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {

					// call DetailItineraryFragment
					Fragment browseItinerary = new DetailItineraryFragment(
							arrItinerary.get(position).getId(), arrItinerary
									.get(position).getItineraryName());
					if (browseItinerary != null) {
						FragmentManager fragmentManager = getFragmentManager();
						FragmentTransaction fTransaction = fragmentManager
								.beginTransaction();
						fTransaction.addToBackStack(null);
						fTransaction.replace(R.id.frame_container,
								browseItinerary).commit();
						getActivity().setTitle(
								arrItinerary.get(position).getItineraryName());
					}
				}
			});
		} catch (Exception e) {
			Log.e("ListItineraryFragment", e.toString());
		}

		return listItineraryFragment;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

		// create option menu in actionbar
		inflater = getActivity().getMenuInflater();
		inflater.inflate(R.menu.list_itinerary_menu, menu);

		// Associate searchable configuration with the SearchView
		searchView = (SearchView) menu.findItem(R.id.action_search_itinerary)
				.getActionView();
		setupSearchView();
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// create event for items of option menu in actionbar
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		AlertDialog dialog;

		switch (item.getItemId()) {
		// show sorter dialog
		case R.id.action_sort_itinerary:
			builder.setTitle("Sort");
			builder.setItems(getResources()
					.getStringArray(R.array.sorter_items),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int item) {
							// sort by sorter
							setSorter(getResources().getStringArray(
									R.array.sorter_items)[item]);
							arrItinerary = itineraryBO.listItinerary(
									getKeyword(), getSorter());
							// reset array Itinerary in adapter
							itineraryAdapter.setArr(arrItinerary);
							itineraryAdapter.notifyDataSetChanged();
						}
					});

			dialog = builder.create();
			dialog.show();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onResume() {
		// on resume change the title of actionbar to Itinerary
		super.onResume();
		getActivity().getActionBar().setTitle("Itineraries");
	}

	public String getSorter() {
		return this.sorter;
	}

	public void setSorter(String sorter) {
		this.sorter = sorter;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String getKeyword() {
		return this.keyword;
	}

	private void setupSearchView() {

		searchView.setIconifiedByDefault(false);
		searchView.setQueryHint("Itinerary Name");

		searchView
				.setOnQueryTextFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View v, boolean hasFocus) {
						// TODO Auto-generated method stub
						if (hasFocus) {
							drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
						} else {
							onClose();
						}
					}
				});
		SearchManager searchManager = (SearchManager) getActivity()
				.getSystemService(Context.SEARCH_SERVICE);

		searchView.setOnQueryTextListener(this);
		searchView.setOnCloseListener(this);
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		setKeyword(query);
		if (getKeyword() != null && getSorter() != null) {
			arrItinerary = itineraryBO.listItinerary(getKeyword(), getSorter());
			itineraryAdapter.setArr(arrItinerary);
			itineraryAdapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		// TODO Auto-generated method stub
		setKeyword(newText);

		if (getKeyword() != null && getSorter() != null) {
			arrItinerary = itineraryBO.listItinerary(getKeyword(), getSorter());
			itineraryAdapter.setArr(arrItinerary);
			itineraryAdapter.notifyDataSetChanged();
			return true;
		} else {
			return false;
		}

	}

	@Override
	public boolean onClose() {
		// TODO Auto-generated method stub
		drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
		searchView.setQuery("", true);
		setKeyword("");
		arrItinerary = itineraryBO.listItinerary("", getSorter());
		itineraryAdapter.setArr(arrItinerary);
		itineraryAdapter.notifyDataSetChanged();
		return true;
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		searchView = null;
		super.onDestroy();
	}

}
